<?php
namespace app\common\model;

use think\Model;

/**
 * 用户token模型
 * Class AdminUser
 * @package app\common\model
 */
class UserToken extends Model
{

    /**
     * 根据用户id查询用户的token
     *
     * @author mayy
     * @date 2017-8-14
     * @param int $user_id
     * @param string $user_type 用户类型
     * @return array
     */
    public function getUserToken($user_id, $user_type = USER_TYPE_ADMIN_USER)
    {
        $return = [];
        if ($user_id <= 0) {
            return $return;
        }

        $where = [
            'user_id'       => $user_id,
            'user_type'     => $user_type,
        ];

        $res = $this->where($where)->find();
        if (!empty($res)) {
             $return = $res->toArray();
        }
        return $return;
    }

    /**
     * 查询一条用户信息
     *
     * @author mayy
     * @date 2017-8-14
     * @param string $token
     * @param string $user_type 用户类型
     * @return array
     */
    public function getToken($token, $user_type = USER_TYPE_ADMIN_USER)
    {
        $return = [];
        if (empty($token)) {
            return $return;
        }

        $where = [
            'token'     => $token,
            'user_type' => $user_type,
        ];

        $res = $this->where($where)->find();
        if (!empty($res)) {
            $return = $res->toArray();
        }
        return $return;
    }

    /**
     * 更新token
     *
     * @author mayy
     * @date 2017-8-14
     * @param $token_id
     * @param array $req
     * @return bool | integer
     */
    public function updateToken($token_id, array $req)
    {
        if ($token_id <= 0) {
            return false;
        }

        $data = $req;
        $data['lasttime'] = time();
        $res = $this->save($data, ['token_id' => $token_id]);
        return $res;
    }

    /**
     * 插入一条token
     *
     * @author mayy
     * @date 2017-8-14
     * @param array $req
     * @return bool | integer
     */
    public function addToken(array $req)
    {
        if (empty($req)) {
            return false;
        }

        $data = $req;
        $data['lasttime'] = time();

        $res = $this->allowField(true)->data($data,true)->isUpdate(false)->save();

        $return = ($res && isset($this->token_id) && $this->token_id > 0) ? $this->token_id : false;
        return $return;
    }
}